package com.android.videotest.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.android.videotest.R;
import com.android.videotest.Urls;
import com.sansecy.android.simplevideo.Player;
import com.sansecy.android.simplevideo.SimpleSurfaceVideoView;

public class SimpleSurfaceVideoActivity extends AppCompatActivity {
    private static final String TAG = "systemVideo-App";
    private ProgressBar mLoadingBar;
    private ProgressBar mProgressBar;

    public static void start(Context context) {
        Intent starter = new Intent(context, SimpleSurfaceVideoActivity.class);
        context.startActivity(starter);
    }

    SimpleSurfaceVideoView videoView;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suface_video);

        String url = Urls.shuangyinqijing;

        TextView tvLoadFailed = findViewById(R.id.tv_load_failed);
        tvLoadFailed.setVisibility(View.GONE);
        mLoadingBar = findViewById(R.id.loadingBar);
        mProgressBar = findViewById(R.id.progressBar);
        mProgressBar.setMax(1000);

        videoView = findViewById(R.id.videoView);
        videoView.loadUrl(url);
//        videoView.loadUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/test_vide.mp4")));
        videoView.setLooping(true);
        videoView.setOnBufferingUpdateListener(new Player.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate( int percent) {
//                mProgressBar.setSecondaryProgress(percent * 1000);
            }
        });
        videoView.setOnInfoListener(new Player.OnInfoListener() {
            @Override
            public boolean onInfo( int what, int extra) {
                if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                    mLoadingBar.setVisibility(View.VISIBLE);
                } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                    mLoadingBar.setVisibility(View.GONE);
                } else if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    mLoadingBar.setVisibility(View.GONE);
                }
                return false;
            }
        });
        videoView.setOnErrorListener(new Player.OnErrorListener() {
            @Override
            public boolean onError( int what, int extra) {
                mLoadingBar.setVisibility(View.GONE);
                mProgressBar.setVisibility(View.GONE);
                tvLoadFailed.setVisibility(View.VISIBLE);
                tvLoadFailed.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        videoView.release();
                        videoView.loadUrl(url);
                        videoView.openVideo();
                        videoView.start();
                    }
                });
                return false;
            }
        });
        videoView.setOnPreparedListener(new Player.OnPreparedListener() {
            @Override
            public void onPrepared() {
//                int duration = mp.getDuration();
//                int newDuar = duration - 10 * 1000;
//                videoView.seekTo(newDuar);
//                Log.d(TAG, "onPrepared() called with: mp = [" + mp + "]");
//                mp.start();
            }
        });
        videoView.setOnCompletionListener(new Player.OnCompletionListener() {

            @Override
            public void onCompletion() {

            }
        });
        videoView.setOnVideoSizeChangedListener(new Player.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(int width, int height) {

            }
        });
        
        // 检查并申请存储权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        } else {
            // 已经有权限，直接播放视频
            startVideoPlayback();
        }
        handler.post(progressRunnable);

        findViewById(R.id.switch_surface).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                videoView.switchSurface();
            }
        });
    }
    
    private void startVideoPlayback() {
        videoView.openVideo();
        videoView.start();
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，开始播放视频
                startVideoPlayback();
            } else {
                // 权限被拒绝，可以显示提示信息
                Log.d(TAG, "存储权限被拒绝");
            }
        }

    }

    private Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            handler.removeCallbacks(progressRunnable);

            int duration = videoView.getDuration();
            if (duration == 0) {
                mProgressBar.setProgress(0);
            } else {
                int currentPosition = videoView.getCurrentPosition();
                float percent = (float) currentPosition / (float)duration;
                mProgressBar.setProgress((int) (percent * 1000));
            }
            handler.post(progressRunnable);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (!videoView.isPlaying()) {
            videoView.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoView.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoView.release();
        handler.removeCallbacks(progressRunnable);
    }
}
